import speech_recognition as sr
import git
import datetime
import os
from colorama import init, Fore, Style
import time
import threading
import sys

init()  # 初始化colorama

def print_colored(text, color=Fore.GREEN):
    """打印彩色文本"""
    print(f"{color}{text}{Style.RESET_ALL}")

def git_push():
    """执行git push操作"""
    try:
        repo = git.Repo(os.getcwd())
        
        # 获取当前时间作为提交信息
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        commit_message = f"自动提交: {current_time}"
        
        # 添加所有更改
        print_colored("正在添加更改...", Fore.YELLOW)
        repo.git.add('.')
        
        # 提交更改
        print_colored("正在提交更改...", Fore.YELLOW)
        repo.git.commit('-m', commit_message)
        
        # 推送到远程仓库
        print_colored("正在推送到Gitee...", Fore.YELLOW)
        repo.git.push('origin', 'master')
        
        print_colored("✓ 成功推送到Gitee！", Fore.GREEN)
        return True
    except Exception as e:
        print_colored(f"错误: {str(e)}", Fore.RED)
        return False

def listen_for_voice():
    """监听语音命令"""
    recognizer = sr.Recognizer()
    
    while True:
        with sr.Microphone() as source:
            print_colored("\n正在监听...(说'保存到gitee'来触发推送，或直接在控制台输入)", Fore.CYAN)
            try:
                audio = recognizer.listen(source, timeout=None)
                print_colored("正在识别...", Fore.YELLOW)
                
                # 使用中文识别
                text = recognizer.recognize_google(audio, language='zh-CN')
                print_colored(f"识别到: {text}", Fore.BLUE)
                
                if "保存到gitee" in text.lower():
                    print_colored("收到语音推送命令！", Fore.GREEN)
                    git_push()
                    
            except sr.UnknownValueError:
                pass  # 忽略无法识别的语音
            except sr.RequestError as e:
                print_colored(f"语音识别服务错误: {e}", Fore.RED)
            
            time.sleep(0.1)

def listen_for_text():
    """监听文本输入"""
    while True:
        try:
            command = input()
            if "保存到gitee" in command.lower():
                print_colored("收到文本推送命令！", Fore.GREEN)
                git_push()
        except Exception as e:
            print_colored(f"文本输入错误: {e}", Fore.RED)

if __name__ == "__main__":
    print_colored("启动自动Git推送程序...", Fore.GREEN)
    print_colored("确保您已经正确配置了Git仓库！", Fore.YELLOW)
    print_colored("您可以通过语音说'保存到gitee'或直接在控制台输入'保存到gitee'来触发推送", Fore.CYAN)
    
    # 创建并启动语音识别线程
    voice_thread = threading.Thread(target=listen_for_voice)
    voice_thread.daemon = True
    voice_thread.start()
    
    # 主线程负责文本输入
    listen_for_text() 